<template>
  <div class="site-wrapper site-page--login">
    <div class="site-content__wrapper">
      <div class="site-content">
        <div class="brand-info">
          <h1 class="brand-info__text">智慧生活</h1>
          <p class="brand-info__intro">www.shujuxiaoyuan.com</p>
        </div>
        <div class="login-main" > 
          <div @click="downloadFile">
            <icon-svg name="pre_icon" style="position: absolute;bottom:10;right:0;width:50px;height:50px" ></icon-svg>
          </div>
          <h3 class="login-title">管理员登录</h3>
          <el-form
            :model="dataForm"
            :rules="dataRule"
            ref="dataForm"
            @keyup.enter.native="dataFormSubmit()"
            status-icon
          >
            <el-form-item prop="userName">
              <el-input v-model="dataForm.userName" placeholder="帐号"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model="dataForm.captcha" placeholder="验证码"></el-input>
                </el-col>
                <el-col :span="10" class="login-captcha">
                  <img :src="captchaPath" @click="getCaptcha()" alt height="36px" />
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item>
              <el-button class="login-btn-submit" type="primary" @click="dataFormSubmit()">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUUID } from "@/utils";
import { JSEncrypt } from "jsencrypt";
export default {
  data() {
    return {
      dataForm: {
        userName: "",
        password: "",
        uuid: "",
        captcha: "",
      },
      messageType: 0,
      publicKey:
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx8wyZzYxaffWrJ4jooN554npe5vD2RSQGNXOY5UZz6hcIW0jdEk1KcdclE7mJPiI2DmgUjBp4Lau+bNmZxmLBqFHUMd29mWyqX+LuYVoymxs8f3VJF+7PqZzuKbtSOyXfcyjIIgtB06YlX4SXx4FCErGRx+MDseN2ObHSPme/3wIDAQAB",
      dataRule: {
        userName: [
          { required: true, message: "帐号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
      },
      captchaPath: "",
    };
  },
  created() {
    // 从cookie获取登录信息，有的话就自动登录
    var userInfo = this.getCookie("shujuxiaoyuan_user");
    if (userInfo || userInfo == "") {
      var data = userInfo.split("!");
      console.log(data);
      // 当前已记录有登录信息，则自动执行登录操作 信息格式为 用户名!加密后的密码
      if (data.length == 2) {
        this.Login(data[0], data[1]);
      }
    }
    // 获取本地登录记录
    var loginName = localStorage.getItem("loginName");
    if (loginName) {
      this.dataForm.userName = loginName;
    }
    this.getCaptcha();
  },
  methods: {
    // 远程卡务软件下载
    downloadFile() {
      this.$http({
        url: this.$http.adornUrl("/api/v1/CardService/getOneCardVersion"),
        method: "post",
        data: this.$http.adornData({
          messageContent: "",
          messageType: this.messageType,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let url = data.messageContent.downloadUrl;
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            `CardCenter${data.messageContent.versionNo}.exe`
          );
          document.body.appendChild(link);
          link.click();
        } else if (data.messageCode == 500) {
          this.$message.error(data.errorMessage);
        } else {
          this.$message.error("未知错误");
        }
      });
    },
    getCookie(key) {
      var str = document.cookie; // 获取所有cookie
      var arr = str.split("; "); // ["name=pengpeng", "age=18", "desc=shuai"]
      // 遍历数组, 找出 键===key时的 value值
      for (var i = 0; i < arr.length; i++) {
        var data = arr[i].split("="); // ["name", "pengpeng"]
        if (data[0] === key) {
          // 如果相等, 说明找到了
          return data[1];
        }
      }
    },
    // 提交表单
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        let encryptor = new JSEncrypt();
        encryptor.setPublicKey(this.publicKey);
        let loginpassword = encryptor.encrypt(
          this.$md5(this.dataForm.password)
        );
        if (valid) {
          // this.isCaptcha(this.dataForm.userName, loginpassword)
          this.Login(this.dataForm.userName, loginpassword);
        }
      });
    },
    // 获取验证码
    getCaptcha() {
      // this.dataForm.uuid = getUUID();
      // this.captchaPath = this.$http.adornUrl(
      //   `/captcha.jpg?uuid=${this.dataForm.uuid}`
      // );
      let timestamp = new Date().valueOf();
      this.$http({
        url: this.$http.adornUrl("/api/v1/PCImageCode"),
        method: "get",
        withCredentials: true,
        responseType: "blob",
      }).then(({ data }) => {
        console.log(data);
        var blob = data;
        var img = document.createElement("img");
        img.onload = function (e) {
          window.URL.revokeObjectURL(img.src);
        };
        this.captchaPath = window.URL.createObjectURL(blob);
      });
    },
    // 验证验证码
    isCaptcha(loginName, loginpassword) {
      this.$http({
        url: this.$http.adornUrl("/api/v1/imageVerifiedCode"),
        method: "post",
        withCredentials: true,
        data: this.$http.adornData({
          messageContent: this.dataForm.captcha,
          messageType: this.messageType,
        }),
      }).then(({ data }) => {
        if (data.messageContent == true && data.messageCode == 200) {
          this.Login(loginName, loginpassword);
        } else {
          this.$message.error("验证码错误");
          this.getCaptcha();
        }
      });
    },
    Login(loginName, loginpassword) {
      // 根据用户guid获取用户的信息
      this.$http({
        url: this.$http.adornUrl("/api/v1/pc-login"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            loginName: loginName,
            loginPassword: loginpassword,
          },
          messageType: this.messageType,
        }),
      }).then(({ data }) => {
        //console.log(data)
        if (data.messageCode == 200) {
          this.userType = data.messageContent.userType;
          if (!data.messageContent.unitGuid) {
            // 没有单位
            if (this.isSysAdmin(this.userType)) {
              this.$message.error("当前系统管理员账户没有所属系统单位");
            } else if (this.isAgent(this.userType)) {
              this.$message.error("当前代理商账户没有所属代理商");
            } else {
              this.$message.error("当前账户管理的学校列表为空");
            }

            return;
          }
          // 保存到cookie中
          document.cookie =
            "shujuxiaoyuan_user=" + loginName + "!" + loginpassword;
          // 保存登录名到本地
          localStorage.setItem("loginName", loginName);
          sessionStorage.setItem("administrator", data.messageContent.userGuid);
          sessionStorage.setItem("identity", data.messageContent.identity);
          sessionStorage.setItem("username", data.messageContent.userName);
          sessionStorage.setItem("userType", data.messageContent.userType);
          sessionStorage.setItem("unitName", data.messageContent.unitName);
          sessionStorage.setItem("unitGuid", data.messageContent.unitGuid);
          sessionStorage.setItem("unitType", data.messageContent.unitType);

          this.$store.commit("user/updateSelectedUnigInfo", {
            unitType: data.messageContent.unitType,
            unitGuid: data.messageContent.unitGuid,
            unitName: data.messageContent.unitName,
          });
          this.$router.push({ path: "/" });
          return;
        }
        if (data.messageCode == 500) {
          this.$message.error(data.errorMessage);
          return;
        } else {
          this.$message.error("登录遇到未知错误");
        }
      });
    },
  },
};
</script>

<style lang="scss">
.site-wrapper.site-page--login {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(38, 50, 56, 0.6);
  overflow: hidden;
  &:before {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
    content: "";
    background-image: url(~@/assets/img/login_bg.jpg);
    background-size: cover;
    background-position: 0 0;
  }
  .site-content__wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: transparent;
  }
  .site-content {
    min-height: 100%;
    padding: 30px 500px 30px 30px;
  }
  .brand-info {
    border-left: 15px solid #fff;
    margin: 220px 100px 0 90px;
    color: #fff;
  }
  .brand-info__text {
    letter-spacing: 18px;
    margin: 0 0 10px 20px;
    font-size: 50px;
    font-weight: 400;
    text-transform: uppercase;
    user-select: none;
  }
  .brand-info__intro {
    margin: 10px 0 10px 20px;
    font-size: 18px;
    line-height: 1.58;
    // opacity: 0.6;
    color: #fff;
  }
  .login-main {
    position: absolute;
    top: 0;
    right: 0;
    padding: 150px 60px 180px;
    width: 470px;
    min-height: 100%;
    // background-color: #17b3a3;
    background-color: #fff;
  }
  .login-title {
    // color: #fff;
    font-size: 16px;
  }
  .login-captcha {
    overflow: hidden;
    > img {
      width: 100%;
      cursor: pointer;
    }
  }
  .login-btn-submit {
    width: 100%;
    margin-top: 38px;
    border: 2px solid #fff;
  }
}
</style>
